<?
set_time_limit(60);

// Configuration area
$tb_threaddir = "/www/threadbuddy-threads/";
$tbrootdir = "/";
$tb_threadfile =  $tb_threaddir . strip_tags($_SERVER[HTTP_HOST]) . "-threads.txt";
$metadir = $tb_threaddir . trim(strip_tags($_SERVER[HTTP_HOST]));
$tb_subthreaddir =  $tb_threaddir . trim(strip_tags($_SERVER[HTTP_HOST])) .  "/";
$tb_metawho = "who.txt";
$tb_timestamp = "newest.txt";
$metats = $tb_threaddir . strip_tags($_SERVER[HTTP_HOST]) . "/" . $tb_timestamp;
$metawho = $tb_threaddir . strip_tags($_SERVER[HTTP_HOST]) . "/" . $tb_metawho;

if (file_exists($tb_threadfile))
    {
    if (filesize($tb_threadfile) > 100000)
       {
       $loadmessage = true;
       }
    }

if (strlen(trim($_GET[tbcolor1]))> 0)
    {
    $tbcolor1 = strip_tags($_GET[tbcolor1]);
    }
else
    {
    $tbcolor1 = "445566";    
    }

if (strlen(trim($_GET[tbcolor2]))> 0)
    {
    $tbcolor2 = strip_tags($_GET[tbcolor2]);
    }
else
    {
    $tbcolor2 = "667788";    
    }

if (strip_tags($_GET[small])==true)
    {
    $tb_width_1 = "375";
    $tb_width_2 = "375";
    $tb_height = 275;
    }
elseif (strip_tags($_GET[fullscreen])==true)
    {
    //$tb_width_1 = "50%";
    //$tb_width_2 = "50%";
    //$tb_height = "100%";
    }
elseif (strlen(trim($_GET[userx1])) > 0 && strlen(trim($_GET[userx2])) > 0 && strlen(trim($_GET[usery])) > 0)
    {
    $tb_width_1 = strip_tags($_GET[userx1]);
    $tb_width_2 = strip_tags($_GET[userx2]);
    $tb_height = strip_tags($_GET[usery]);
    }
else
    {
    $tb_width_1 = "500";
    $tb_width_2 = "500";
    $tb_height = 400;    
    }

if (strip_tags($_GET[long])=="true")
    {
    $tb_height = 600;
    }

global $thispage;
$tbfont = "verdana, geneva, helvetica, arial";
//$tbfont = '"Trebuchet MS", Trebuchet, Verdana, Arial, Helvetica, sans-serif';
$thispage = "threadbuddy.php";

//$comment_length = round($tb_width / 7,0);
$comment_length = 40;

//print_r($_SERVER);

$val = $_SERVER[REQUEST_URI];

// Guard against unsavory things in the REQUEST_URI var
switch ($_SERVER[REQUEST_URI])
   {
   // This is stuff that shouldn't exist in URL encoded URLs
   //case (stripos($val,"http:") !== false): $spammer=true; break;
   //case (stripos($val,"ftp:") !== false): $spammer=true; break;
   //case (stripos($val,"../") !== false): $spammer=true; break;  
   }
if ($spammer==true)
   {
   echo "Spammer!";
   exit();
   }

function about()
  {
  global $tbfont, $tbbackground;
  echo "<title>About Thread Buddy</title>";
  echo "<body style='background:#333333;color:#ffffff;font-family:". $tbfont .";'>";
  echo "<h3>About Thread Buddy</h3>";
  echo "The Thread Buddy is a threaded discussion tool that uses wildcard DNS, so you can pick your own discussion URL.
        The thread is tied to the *.". strip_tags($_SERVER[HTTP_HOST]) ." URL that you choose, so there are endless open \"channels\" to use. The thread buddy is search engine
        friendly since it has an integrated plaintext and rss feed.  Also, the thread buddy can easily be integrated
        into any site.  See the <a style='color:#ccccff;' href='". $tbrootdir ."?a=help'>help</a> page for how to integrate a Thread Buddy into your site.";
  echo "<p>";
  echo "The Thread Buddy was created by <a href='http://rob.sun3.org' style='color:#ccccff;'>Robert Thompson</a>";
  echo "<br>";
  echo "<br><img src='myemail.jpg'>";
  echo "<p>";
  echo "<a href='index.php' style='color:#ccccff;'>Go back to the Thread Buddy</a>";
  echo "</body>";    
  }

function help()
  {
  global $tbfont, $tbbackground;
  echo "<title>Thread Buddy Help and Tutorial</title>";  
  echo "<body style='background:#333333;color:#ffffff;font-family:". $tbfont .";'>";
  echo "<h2 style='color:yellow;'>Thread Buddy Help</h2>";
  echo "You can either use the threadbuddy.com site directly or you can integrate a Thread Buddy into your own site.  There is no need to request a new discussion forum for your site
        as discussion threads are tied to the URL that you choose at threadbuddy.com.  Any name preceeding the .threadbuddy.com will work.  To start a new
        discussion forum, simply put a name of your choice before the .threadbuddy.com in your browser (example: my-own-forum.threadbuddy.com).";
  echo "<h3 style='color:yellow;'>General Discussion</h3>";
  echo "&nbsp;&nbsp;<a style='color:orange;' href='http://general.threadbuddy.com'>http://general.threadbuddy.com</a>";
  echo "<h3 style='color:yellow;'>Installation Help</h3>";
  echo "&nbsp;&nbsp;<a style='color:orange;' href='http://installation.threadbuddy.com'>http://installation.threadbuddy.com</a>";
  echo "<h3 style='color:yellow;'>Integration Help</h3>";
  echo "&nbsp;&nbsp;<a style='color:orange;' href='http://integration.threadbuddy.com'>http://integration.threadbuddy.com</a>";
  echo "<h3 style='color:yellow;'>Bugs</h3>";
  echo "&nbsp;&nbsp;<a style='color:orange;' href='http://bugs.threadbuddy.com'>http://bugs.threadbuddy.com</a>";
  echo "<h3 style='color:yellow;'>Discussion Tags - Images and Links</h3>";
  echo "You can include images by using the tag 'image:http://mycompany.com/image.png'.  Also, links of the form 'http://mycompany.com' will always be converted to a clickable URL.";
  echo "<h3 style='color:yellow;'>Customization and Site Integration</h3>";
  echo "It is easy to add a Thread Buddy to your site!  Just replace the URL in the iframe tag below with your own thread buddy (<i>yourname</i>.threadbuddy.com), it's that simple.";
  echo "At a minimum, the following is code is all that is needed to put a Thread Buddy on your site:";
  echo "<p>";
  echo "<p><code>&nbsp;&nbsp;";  
  echo htmlentities("<iframe width=1021 height=678 scrolling=no frameborder=no src='http://mysite.threadbuddy.com?iframe=true'></iframe>");
  echo "</code><p>";          
  echo "<p>Below are a few things that you can <b>optionally</b> put in the URL line of your iframe tag to customize your Thread Buddy.";          
  echo "<h4 style='color:orange;'>Username/Alias Integration</h4>";  
  echo "If you have a site with users who log in and would like to integrate their usernames with Thread Buddy aliases, these 
        options allow you to set an initial alias for the user and to optionally lock the user from changing the alias by disabling the alias field. ";
  echo "<ul>";
  echo "<li><b>sitealias</b>=[login_name]</li>";
  echo "<li><b>aliaslock</b>=true</li>";  
  echo "</ul>";
  echo "<p>";
  echo "Putting this all together,
        this is what that may look like if you happen to be using PHP for your site and are using PHP \$_SESSION variables:";
  echo "<p>";
  echo "<p><code>&nbsp;&nbsp;";  
  echo htmlentities("<iframe width=771 height=524 scrolling=no frameborder=no src='http://mysite.threadbuddy.com?sitealias=<". chr(63) . ' echo urlencode($_SESSION[user]); ' . chr(63) .">&aliaslock=true&iframe=true'></iframe>");
  echo "</code><p>";          
  echo "<h4 style='color:orange;'>Changing your Thread Buddy Colors</h4>";
  echo "<ul>";      
  echo "<li><b>tbbackground</b>=112233<br><br><i>The background color while the Thread Buddy is called with the iframe=true flag.  This allows you to fudge a little on the 
        size of your iframe window and it will still match the background of your site.</i><br><br></li>";
  echo "<li><b>tbcolor1</b>=115588<br><br><i>Replace the color around the comment box (exclude the '#')</i><br><br></li>"; 
  echo "<li><b>tbcolor2</b>=229966<br><br><i>Replace the color around the peer and top menu area (exclude the '#')</i><br><br></li>";  
  echo "</ul>";
  echo "<p><code>&nbsp;&nbsp;";  
  echo htmlentities("<iframe width=771 height=512 scrolling=no frameborder=no src='http://threadbuddy.com?iframe=true&small=true&tbcolor1=115588&tbcolor2=229966'></iframe>");
  echo "</code><p>";  
  echo "<iframe width=771 height=512 scrolling=no frameborder=no src='http://threadbuddy.com?iframe=true&small=true&tbcolor1=115588&tbcolor2=229966&tbbackground=333333'></iframe>";  
  echo "<h4 style='color:orange;'>Sizing your Thread Buddy</h4>";
  echo "<p>";
  echo "You can use the pre-defined large (default) or small versions or specify a custom width and height for your threadbuddy to make it fit your page perfectly:";
  echo "<ul>";  
  echo "<li><b>small</b>=true<br><br><i>A small version of the threadbuddy (width and height values are preset).  This overrides the custom settings below.</i></li>";
  echo "</ul>";
  echo "<ul>";      
  echo "<li><b>userx1</b>=250<br<br><i>The width of the discussion thread list (left) window.</i><br><br></li>";
  echo "<li><b>userx2</b>=250<br><br><i>The width of the thread detail / comment (right) window.</i><br><br></li>"; 
  echo "<li><b>usery</b>=450<br><br><i>The height of the 2 windows.</i><br></li>";  
  echo "</ul>";
  echo "<p>";
  echo "A Custom Size (userx1,userx2,usery) Thread Buddy";  
  echo "<p><code>&nbsp;&nbsp;";
  echo htmlentities("<iframe width=621 height=369 scrolling=no frameborder=no src='http://threadbuddy.com?userx1=350&userx2=350&usery=150&iframe=true'></iframe>");
  echo "</code><p>";
  echo "<iframe width=600 height=469 scrolling=no frameborder=no src='http://threadbuddy.com?userx1=260&userx2=350&usery=150&iframe=true&tbbackground=333333'></iframe>";
  echo "<p>";    
  echo "The small=true Thread Buddy";  
  echo "<p><code>&nbsp;&nbsp;";
  echo htmlentities("<iframe width=771 height=512 scrolling=no frameborder=no src='http://threadbuddy.com?iframe=true&small=true'></iframe>");
  echo "</code><p>";
  echo "<iframe width=771 height=512 scrolling=no frameborder=no src='http://threadbuddy.com?iframe=true&small=true&tbbackground=333333'></iframe>";
  echo "<p>";
  echo "Regular sized Thread Buddy";  
  echo "<p><code>&nbsp;&nbsp;";
  echo htmlentities("<iframe width=1021 height=666 scrolling=no frameborder=no src='http://threadbuddy.com?iframe=true&tbbackground=333333'></iframe>");
  echo "</code><p>";
  echo "<iframe width=1021 height=666 scrolling=no frameborder=no src='http://threadbuddy.com?iframe=true&tbbackground=333333'></iframe>";
  echo "<p>";
  echo "<a href='". $tbrootdir ."' style='color:#ccccff;'>Go back to the Thread Buddy</a>";
  echo "</body>";    
  }


function tb_initthreadfile()
   {
   global $tb_threadfile;
   if (!file_exists($tb_threadfile))
      {
      if (file_put_contents($tb_threadfile,""))
         {
         echo "New threadfile created";
         }
      }
   }

function rssheader()
    {
    echo "<" . chr(63) . "xml version=\"1.0\" encoding=\"UTF-8\"" . chr(63) . ">" ."\n";
    echo '<rss version="2.0">' . "\n";
    echo '<channel>' . "\n";
    echo '<title>' . "\n";
    echo '<![CDATA['. strip_tags($_SERVER[HTTP_HOST]) .']]>' . "\n";
    echo '</title>' . "\n";
    
    echo '<description>' . "\n";
    echo '<![CDATA[Comments]]>' . "\n";
    echo '</description>' . "\n";
    
    echo '<link>http://' . strip_tags($_SERVER[HTTP_HOST])  . "</link>\n";
    echo '<copyright><![CDATA['. strip_tags($_SERVER[HTTP_HOST]) .']]></copyright>' . "\n";
    echo '<generator>Thread Buddy</generator>' . "\n";
    }
    
function rssfooter()
    {
    echo '</channel>' . "\n";
    echo '</rss>' . "\n";
    }
    	
function tb_get_child($full_array,$parent,$ape,$depth,$format=false,$outputsub)
   {   
   global $comment_length, $tb_maxdate, $tout;
   $outline = array();
   //$outlinesub = array();
   
   //print_r($full_array);
   
   // Return all of the children of the parent in a multi-dimensional array
   if ($parent=="none")
      {
      // This is the root array, output the root parents
      if (is_array($full_array))
         {
         foreach ($full_array as $key => $val)
            {
            if (trim($val[1]) == "")
               {                              
               if ($format==false)
                  {
                  $output = "<img src='dot.gif' border=0>&nbsp;";
                  }
               
               $comment = trim(stripslashes(base64_decode($val[4])));
               if (strlen($comment) > $comment_length)
                  {
                  $comment = substr($comment,0,$comment_length) . "..";
                  }
               
               if ($format==false)
                  {
                  $thisdate = intval(substr($val[0],11,10)); 
                  if ( $thisdate > $tb_maxdate)
                      {
                      $tb_maxdate = $thisdate;
                      }
                  $output .= "<span id='selectedtb". $val[0] ."' name='selectedtb" . $val[0] ."'>
                        <a href='javascript:tb_getmsg(\"none\",\"". $val[0] ."\")'>
                        " . str_replace("[tbbr]"," ",$comment) . "</a>";
                  $output .= "&nbsp;&nbsp;<font color='black'>(" . $val[3] . ")&nbsp;" . date("m/d/y h:ia", $thisdate) ."</font></span>";
                  $output .= "</span><br>";
                  }
               elseif ($format=="rss")
                  {
                  if ($ape==$val[0])
                     {
                     tb_getmsg("none",$val[0],$format);
                     }
                  else
                     {
                     tb_getmsg($ape,$val[0],$format);                     
                     }
                  }	
               else
                  {
                  echo "<hr style='color:#eeeeee;'>New thread started by <b>". $val[3] ."</b> on <b>" . date("m/d/y h:ia",substr($val[0],11,10)) . "</b><br><br>";
                                                 
                  if ($ape==$val[0])
                     {
                     tb_getmsg("none",$val[0],$format);
                     }
                  else
                     {
                     tb_getmsg($ape,$val[0],$format);                     
                     }
                  }
                                 
               $tout = $output;           
               tb_get_child($full_array,$val[0],$ape,$depth + 1,$format,$outputsub);
               }
            }
         }
      }
   else 
      {
      $full_array = array_reverse($full_array);
      //$outputsubarray = array();
      foreach ($full_array as $key => $val)
         {
         
         if (trim($val[1]) == $parent)
            {
            if ($format!="rss")
               {
               $outputsub = "<span class='spacerclass'>";
               for ($i=0;$i<$depth;$i++)
                  {
                  $outputsub .= "&nbsp; &nbsp; &nbsp;";
                  }
               $outputsub .= "</span>";
               }
            if ($format==false)
               {
               $outputsub .= "<img src='rose.png' border=0>&nbsp;";
               }
            $comment = trim(stripslashes(base64_decode($val[4])));
            if (strlen($comment) > $comment_length)
               {
               $comment = substr($comment,0,$comment_length) . "..";
               }
            
            if ($format==false)
               {
               $thisdate = intval(substr($val[0],11,10)); 
               if ( $thisdate > $tb_maxdate)
                   {
                   $tb_maxdate = $thisdate;
                   }               										
               $outputsub .= "<span id='selectedtb". $val[0] ."' name='selectedtb" . $val[0] ."'><a href='javascript:tb_getmsg(\"". $ape ."\",\"". $val[0] ."\")'>" . str_replace("[tbbr]"," ",$comment) . "</a>";
               $outputsub .= "&nbsp;&nbsp;<font color='black'>(" . $val[3] . ")&nbsp;" . date("m/d/y h:ia",$thisdate) ."</font></span>";
               $outputsub .= "<br />";
               }
            elseif ($format=="rss")
               {
               tb_getmsg($ape,$val[0],$format);
               }
            else
               {
               //$outputsub .= "<hr style='color:#eeeeee;'>";
               tb_getmsg($ape,$val[0],$format);              
               }
            $tout .= $outputsub;                                          
            tb_get_child($full_array,$val[0],$ape,$depth + 1,$format,$outputsub);                        
            }            
         }		         
      }
   return $tout;                              
   }
	
function tb_loadthreads($format=false)
   {
   global $tb_threadfile, $tb_subthreaddir, $tb_maxdate,$tbrootdir;
   tb_initthreadfile();
   
   // Now, we are going to go into the main threadfile and get the parent threads
   // The load up all the subthread files that are associated and put them in one big array
   
   // Load up the main threadfile
   $tb_array = file($tb_threadfile); 
   $tb_array = array_reverse($tb_array);
   
   $datearray = array(); 
   $add_array = array();
   $mainarray = array();
  
   // Load up the contents of all the subthread files
   for ($i=0;$i<sizeof($tb_array);$i++)
      {
      $mainarray[$i] = explode("|",$tb_array[$i]);
      // Add this to the most recently posted date array
      array_push($datearray,substr($mainarray[$i][0],11,10));   
      $tb_subthreadfile = $tb_subthreaddir . "thread-" . trim($mainarray[$i][0]) . ".txt";
      if (file_exists($tb_subthreadfile))
         {
         // Eventually add support for skipping archived threads here
         $parent = $mainarray[$i][0];
         $add_array[$parent] = file($tb_subthreadfile);
         }
      }
   
   $outarray = array();

   $output = "";
   $tb_maxdate = 0;

   // Inject the add_array into the carray array where appropriate
   for ($i=0;$i<sizeof($mainarray);$i++)
      {
      // Add the subthread entries
      $parent = $mainarray[$i][0];
      array_push($outarray,$mainarray[$i]);
      for ($j=0;$j<sizeof($add_array[$parent]);$j++)
         {
         $temparray = explode("|",$add_array[$parent][$j]);
         array_push($outarray,$temparray);
         array_push($datearray,substr($temparray[0],11,10));   
         }
      // $outarray = array_reverse($outarray);
      // Add the main thread start
      //print_r($mainarray);
      $alltout .= tb_get_child($outarray,"none",$mainarray[$i][0],0,$format,"");
      $outarray = array();         
      // Add this to the most recently posted date array
      }

   if ($format==false)
      {
      echo $tb_maxdate . "[|tbmaxdate|]";
      }
   elseif ($format=="plain")
      {
      echo "<a href='". $tbrootdir ."index.php'>View Threaded Version</a><br>";
      }

   echo $alltout;
   }


function tb_setmath()
   {
   $_SESSION[math1] = rand(1,10);
   $_SESSION[math2] = rand(1,10);
   }


function duration($secs)
   {
   $vals = array('w' => (int) ($secs / 86400 / 7),
   'd' => $secs / 86400 % 7,
   'h' => $secs / 3600 % 24,
   'm' => $secs / 60 % 60,
   's' => $secs % 60);
   $ret = array();
   $added = false;
   foreach ($vals as $k => $v) 
      {
      if ($v > 0 || $added) 
         {
         $added = true;
         $ret[] = $v . $k;
         }
      }
   return join(' ', $ret);
   } 

function loadnewest()
   {
   global $tb_threadfile, $tb_subthreaddir, $tb_maxdate,$tbrootdir;
   $all = file ($tb_threadfile);
   $exploded = explode("|",$all[sizeof($all)-1]);
   echo $exploded[0];
   }

function tb_updatemeta()
   {
   /*  Peers information is stored in this format:
   1207495894|75.45.94.12
   1207421031|75.45.94.12
   1207421023|75.45.94.12
   1207421011|75.45.94.12
   */
   global $tb_threaddir, $tb_timestamp, $metats, $metadir, $metawho;
   
   // Create the directory and file if they don't exist
   if (!is_dir($metadir))
      {
      mkdir($metadir);      
      }
      
   // See if the metafile exists
   if (file_exists($metawho))
      {
      // Load what's there into an array
      $metaarray = file($metawho);      
      }
   else
      {
      // Create an empty array if a file does not exist
      $metaarray = array();
      }
   
   // Create *this* timestamp that is to be added to the peers file
   if (strlen(trim(strip_tags($_GET[alias]))) == 0)
      {
      $data = time() . "|" . $_SERVER[REMOTE_ADDR];
      }
   else
      {
      $data = time() . "|" . strip_tags($_GET[alias]);      
      }

   // Add *this* peer info to the end of the metafile      
   array_push($metaarray,$data);
   
   // Reverse sort the peer array
   rsort($metaarray);
   
   // Create our output to be written back to the file
   for ($i=0;$i<10;$i++)
      {
      // Check for empty lines as we don't want files to grow from the extra \n 
      if (strlen(trim($metaarray[$i]))> 0)
         {         
         $fileput .= trim($metaarray[$i]) . "\n";
         }
      }
   
   // Write the peer file back
   file_put_contents($metawho,$fileput);
   
   // Get the contents of the file again
   $output = file($metawho);
   
   // create a new array to hold the output
   $who = array();
   
   // Loop through and find the people who are here less than x time ago
   for ($i=0;$i<sizeof($output);$i++)
      {
      $exploded = explode("|",$output[$i]);
      $rightnow = time();
      $twentysecondsago = intval($rightnow) - 25;
      if (((intval(trim($exploded[0]))) > $twentysecondsago) && $i <= 8)
         { 
         array_push($who,$exploded[1]);
         }
      }

   // Only show unique people        
   $who = array_unique($who);  
   
   // Get the most recent timestamp
   $ts = file_get_contents($tb_timestamp);
   echo $ts . "[|tbmaxdate|]";
   
   if (strlen(trim($ts))> 0)
      {
      $ago = time() - intval(trim($ts));
      $duration = duration($ago);
      if (strlen(trim($duration)) > 0)
         {
         echo "<b style='font-size:11px'>Last Post</b><br>". $duration  ." ago<br>";
         }
      }
   echo "<b style='font-size:11px'>Online Peers</b><br>";   
   foreach ($who as $key => $val)
      {
      echo $val . "<br>";
      }
   }

function tb_getmsg($ape,$threadid,$format)
   {
   global $tb_threadfile, $tb_subthreaddir;
   tb_initthreadfile();
            
   if (trim($ape)=="none")
       {
       $tb_array = file($tb_threadfile);
       }
   else
       {
       $tb_subthreadfile = $tb_subthreaddir . "thread-" . trim($ape) . ".txt";
       $tb_array = file($tb_subthreadfile);    
       }   
   
   for ($i=0;$i<sizeof($tb_array);$i++)
      {
      if (substr($tb_array[$i],0,21) == $threadid)
         {
         $carray = explode("|",$tb_array[$i]);
         $msgbody = str_replace("[tbbr]","<br>",stripslashes(base64_decode($carray[4])));
         $msgbodyafter = ereg_replace("image:([[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/])", "<img border=0 src=\"\\1\">", $msgbody);
         if (strlen($msgbodyafter) == strlen($msgbody))
            {
            $msgbody = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]", "<a target='_blank' href=\"\\0\">\\0</a>", $msgbody);
            }
         else
            {
            $msgbody = $msgbodyafter;
            }

         if ($format=="rss")
            {
            echo "<item>\n";			   
            echo "<title><![CDATA[";
            echo "Comment by: " . stripslashes($carray[3]);             
            echo "]]></title>\n";
            echo "<description><![CDATA[";
            echo $msgbody;    
            echo "]]></description>\n";
            // Format date in RSS style	
            echo "<pubDate>". date("D, d M Y H:i:s -0400",substr($carray[0],11,10)) ."</pubDate>\n";
            $this_host = strip_tags($_SERVER[HTTP_HOST]);
            $thisurl = "http://". $this_host;         
            echo "<link>" . $thisurl . "?tid=". $threadid ."</link>\n";
            echo "<guid>" . $thisurl. "?tid=". $threadid ."</guid>\n";
            echo "</item>\n";                           		   
            }    			
         else
            {
            echo "<span class='msgfooter' id='msgfooter' name='msgfooter'>";
            echo "&nbsp;Posted by <b>" . stripslashes($carray[3]) . "</b> on <b>" . date("m/d/y h:ia",substr($carray[0],11,10)) ."</b>&nbsp;</span><p>";            
            echo "<pre>" . $msgbody . "</pre>";
            }
         }
      }
   }

function tb_addcomment($comment,$childof,$ape,$alias)
   {
   global $tb_threaddir, $tb_timestamp, $tb_subthreaddir;
   
   $metadir = $tb_threaddir . strip_tags($_SERVER[HTTP_HOST]);
   // Get rid of any PHP and/or HTML in there.
   $comment = htmlentities($comment);
   
   if (strlen(trim($alias)) == 0)
      {
      $alias = $_SERVER[REMOTE_ADDR];
      }
   
   // Don't allow an empty comment
   if (strlen(trim($comment)) == 0)
      {
      exit();
      }
   
   if (strlen(trim($alias)) == 0)
      {
      $alias = "Anonymous";		
      }
	
   // Set a cookie for the alias
   setcookie("tbalias",$alias,time() + 60 * 60 * 24 * 365);
   
   // Make sure that the browser can do simple math
   $number1 = str_replace(".","",$_SERVER[REMOTE_ADDR]);
   $number2 = strlen($alias);
   $number3 = $number1 - $number2;

   if ($_POST[key] != $number3)
      {
      exit();
      }
   
   global $tb_threadfile;
   
   $id = microtime();
   $id = str_replace(" ","_",$id);
   
   if (strlen(trim($childof)) > 0)
      {
      if (strtolower(trim($ape))=="none")
         {
         $ape = $childof;
         }
      $fstring = $id . "|" . $childof . "|" . $_SERVER[REMOTE_ADDR] . "|" . $alias . "|" . base64_encode(str_replace("\n","[br]",$comment)) . "\n";
      $tb_subthreadfile = $tb_subthreaddir . "thread-" . trim($ape) . ".txt";
      file_put_contents($tb_subthreadfile,$fstring,FILE_APPEND);      
      }
   else 
      {
      $fstring = $id . "||" . $_SERVER[REMOTE_ADDR] . "|" . $alias . "|" . base64_encode($comment) . "\n";
      // If this is not a child of another thread (i.e. is a root thread), we put it in the main threadfile 
      file_put_contents($tb_threadfile,$fstring,FILE_APPEND);
      }
         
   // Add the most recent timestamp to the timestamp file in the metadir
   $metats = $tb_threaddir . strip_tags($_SERVER[HTTP_HOST]) . "/" . $tb_timestamp;
   file_put_contents($metats,substr($id,11,10));
   }

switch ($_GET[a]) 
   {
   case "about":
      about();
      exit();
      break;
   case "help":
      help();
      exit();
      break;
   case "loadthreads":	
      tb_loadthreads(false);
      exit();
      break;
   case "loadnewest":
      loadnewest();
      exit();
      break;
   case "viewplain":
      tb_loadthreads("plain");
      exit();
      break;
   case "rss":
      rssheader();
      tb_loadthreads("rss");
      rssfooter();
      exit();
      break;
   case "getmath":
      session_start();
      tb_setmath();	  
      // Generate a new posting math problem for the client javascript to solve
      echo $_SESSION[math1] . "|" . $_SESSION[math2];
      exit();
      break;
   case "addcomment":
      session_start();	  
      $passedanswer = intval($_POST[answer]);
      $answer = intval($_SESSION[math1]) + intval($_SESSION[math2]);
      if ($answer == $passedanswer)
         {	  
         tb_addcomment($_POST[data],$_POST[childof],$_POST[ape],$_POST[tbalias]);
         }
      tb_loadthreads(false);
      exit();
      break;
   case "viewthread":  	
      tb_getmsg($_GET[ape],$_GET[data],false);
      exit();
      break;
   case "updatemeta":
      tb_updatemeta($_GET[data]);
      exit();
      break;
   default:
      break;
   }
?>

<script type='text/javascript'>

// XML/RPC stuff
var xmlhttp
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
  try {
  xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
 } catch (e) {
  try {
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
  } catch (E) {
   xmlhttp=false
  }
 }
@else
 xmlhttp=false
@end @*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
 try {
  xmlhttp = new XMLHttpRequest();
 } catch (e) {
  xmlhttp=false
 }
}

// XML/RPC stuff
var xmlhttplt
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
  try {
  xmlhttplt=new ActiveXObject("Msxml2.XMLHTTP")
 } catch (e) {
  try {
    xmlhttplt=new ActiveXObject("Microsoft.XMLHTTP")
  } catch (E) {
   xmlhttplt=false
  }
 }
@else
 xmlhttplt=false
@end @*/
if (!xmlhttplt && typeof XMLHttpRequest!='undefined') {
 try {
  xmlhttplt = new XMLHttpRequest();
 } catch (e) {
  xmlhttplt=false
 }
}

// XML/RPC stuff
var xmlhttpmeta
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
  try {
  xmlhttpmeta=new ActiveXObject("Msxml2.XMLHTTP")
 } catch (e) {
  try {
    xmlhttpmeta=new ActiveXObject("Microsoft.XMLHTTP")
  } catch (E) {
   xmlhttpmeta=false
  }
 }
@else
 xmlhttpmeta=false
@end @*/
if (!xmlhttpmeta && typeof XMLHttpRequest!='undefined') {
 try {
  xmlhttpmeta = new XMLHttpRequest();
 } catch (e) {
  xmlhttpmeta=false
 }
}

// XML/RPC stuff
var xmlhttpmath
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
  try {
  xmlhttpmath=new ActiveXObject("Msxml2.XMLHTTP")
 } catch (e) {
  try {
    xmlhttpmath=new ActiveXObject("Microsoft.XMLHTTP")
  } catch (E) {
   xmlhttpmath=false
  }
 }
@else
 xmlhttpmath=false
@end @*/
if (!xmlhttpmath && typeof XMLHttpRequest!='undefined') {
 try {
  xmlhttpmath = new XMLHttpRequest();
 } catch (e) {
  xmlhttpmath=false
 }
}

// XML/RPC stuff
var xmlhttpnewest
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
  try {
  xmlhttpnewest=new ActiveXObject("Msxml2.XMLHTTP")
 } catch (e) {
  try {
    xmlhttpnewest=new ActiveXObject("Microsoft.XMLHTTP")
  } catch (E) {
   xmlhttpnewest=false
  }
 }
@else
 xmlhttpnewest=false
@end @*/
if (!xmlhttpnewest && typeof XMLHttpRequest!='undefined') {
 try {
  xmlhttpnewest = new XMLHttpRequest();
 } catch (e) {
  xmlhttpnewest=false
 }
}

var updating = 0;

<?
if ($_GET[fullscreen] == "true")
   {
   echo "window.onresize = resize;\n";
   }
?>



function tbpopup()
   {
   var site = "http://<? echo $_SERVER[SERVER_NAME] . $tbrootdir ; ?>?iframe=true&fullscreen=true";
   window.open(site,"ThreadBuddy","toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=0,resizeable=1,width=1000,height=700");
   
   } 
   
function resize()
   {
   // Resize the thread div as Firefox will not contain the contents in fullscreen mode by itself
   if (window.innerHeight)
      {
      var winheight = window.innerHeight;
      document.getElementById('tb_threads').style.height =  (winheight - 251) + "px";
      document.getElementById('tb_msg').style.height = (winheight - 251) + "px";
      }
   }

function gup(name)
   {
   name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
   var regexS = "[\\?&]"+name+"=([^&#]*)";
   var regex = new RegExp( regexS );
   var results = regex.exec( window.location.href );
   if( results == null )
    return "";
   else
    return results[1];
   }

function pageload()
   {
   var tid = gup('tid');
   loadthreads(tid);
   updatemeta();
   tb_getmath();  
   setInterval("updatemeta()",10000);
   loadnewest();
   }

function newchan()
   {
   var min=10000000;
   var max=99999999;
   var randomnumber=Math.floor(Math.random() * (max - min + 1) + min)
   var url = "http://" + randomnumber + ".<? echo $_SERVER[SERVER_NAME] . $tbrootdir; ?>";
   window.location = url;	
   }
	
function loadthreads(tid)
   {
   <?
   if ($loadmessage == true)
      {
      //echo "document.getElementById('tb_threads').innerHTML = \"Loading Threads...\";";
      }
   ?>
   // Get first list of arguments.
   url="<? echo $tbrootdir . $thispage; ?>?sid=" + Math.random()+ "&a=loadthreads";
   
   xmlhttplt.open("GET",url,true);
   xmlhttplt.onreadystatechange=function()
      {
      if (xmlhttplt.readyState==4)
         {
         var response = xmlhttplt.responseText;
         var response2 = response.split("[|tbmaxdate|]");
         var maxdate = response2[0];
         document.getElementById('newest').value = maxdate;
         response = response2[1];
         document.getElementById('tb_threads').innerHTML = response;
         // If we have currently have a thread we are working one, let's highlight that one again
         if (document.getElementById('threadid'))
            {
            if (document.getElementById('threadid').value != "none" && document.getElementById('threadid').value != "")
               {
               var selectedthread;
               selectedthread = "selectedtb" + document.getElementById('threadid').value;
               document.getElementById(selectedthread).className='selectedtb';
               tb_getmsg(document.getElementById('ape').value,document.getElementById('threadid').value);            
               }
            }
         
         if (tid)
            {
            if (tid.length > 0)
               {
               tb_getmsg(tid);
               }               
            }
<?
         if ($_GET[fullscreen] == "true")
            {
            echo "resize();\n";
            }
?>

         }
      };
   
   xmlhttplt.setRequestHeader('Accept','message/x-jl-formresult');
   xmlhttplt.send(null);
   return false;	
   }

function tb_getmath()
   {
   // Get first list of arguments.
   url="<? echo $tbrootdir . $thispage; ?>?sid=" + Math.random()+ "&a=getmath";      
   xmlhttpmath.open("GET",url,true);
   xmlhttpmath.onreadystatechange=function()
      {
      if (xmlhttpmath.readyState==4)
         {
         var response = xmlhttpmath.responseText;
         var response2 = response.split("|");
         document.getElementById('math1').value = response2[0];
         document.getElementById('math2').value = response2[1];
         }
      };
   
   xmlhttpmath.setRequestHeader('Accept','message/x-jl-formresult');
   xmlhttpmath.send(null);
   return false;	
   }

function loadnewest()
   {
   // Get first list of arguments.
   url="<? echo $tbrootdir . $thispage; ?>?a=loadnewest";
   xmlhttpnewest.open("GET",url,true);
   xmlhttpnewest.onreadystatechange=function()
      {
      if (xmlhttpnewest.readyState==4)
         {
         var response = xmlhttpnewest.responseText;
         tb_getmsg("none", response);
         }
      };

   xmlhttpnewest.setRequestHeader('Accept','message/x-jl-formresult');
   xmlhttpnewest.send(null);
   return false;
   }
   
function updatemeta()
   {
   var tbalias=document.getElementById('tbalias').value;
   var newest=document.getElementById('newest').value;
   var url="<? echo $tbrootdir . $thispage; ?>?sid=" + Math.random()+ "&a=updatemeta&alias=" + tbalias;
   xmlhttpmeta.open("GET",url,true);
   xmlhttpmeta.onreadystatechange=function()
      {
      if (xmlhttpmeta.readyState==4)
         {
         var response = xmlhttpmeta.responseText;
         var response2 = response.split("[|tbmaxdate|]");
         var maxdate = response2[0];
         var peers = response2[1];
         var maxts = response2[0];
         if (newest < maxdate)
            {
            loadthreads();
            }
         document.getElementById('tb_meta').innerHTML = peers;
         }
      };
   
   xmlhttpmeta.setRequestHeader('Accept','message/x-jl-formresult');
   xmlhttpmeta.send(null);
   return false;	
   }

function tb_getmsg(ape,msg)
   {
   //document.getElementById('tb_msg').innerHTML = "Loading...";
   // Get first list of arguments.
   url="<? echo $tbrootdir . $thispage; ?>?sid=" + Math.random()+ "&a=viewthread&data=" + msg + "&ape=" + ape;
   
   // Unset the other selectedtb spans to set them back to unselected.
   var spans;
   spans = document.getElementsByTagName('span');
   
   var selectedthread;
   selectedthread = "selectedtb" + msg;
   
   for (var i = 0; i < spans.length; i++)
      {
      var span = spans[i];
      if ((span.id.substr(0,10) == "selectedtb") && span.id != selectedthread)
         {
         document.getElementById(span.id).className='unselectedtb';
         }
      }
   
   if (document.getElementById(selectedthread))
      {
      document.getElementById(selectedthread).className='selectedtb';
      }
      
   xmlhttp.open("GET",url,true);   
   xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4)
         {
         response = xmlhttp.responseText;
         document.getElementById('tb_msg').innerHTML = response;
         document.getElementById('commenttypereply').disabled = false;
         //document.getElementById('commenttypereply').checked = true;
         //document.getElementById('commenttypenew').checked = false;
         document.getElementById('threadid').value = msg;
         document.getElementById('ape').value = ape;         
         }
      };
   
   xmlhttp.setRequestHeader('Accept','message/x-jl-formresult');
   xmlhttp.send(null);
   //return false;	
   }

function tb_addcomment()
   {
   // Have the users browser do some simple math to make sure it has a brain (not a spammer)
   var number1;
   var number2;
   var number3;
   if (document.getElementById('tbalias').value=="")
      {
      alert('Empty alias, cannot post.');
      loadthreads();
      exit();
      }
   else
      {
      number1 = document.getElementById('tbalias').value.length;      
      }
   
   number2 = "<? echo str_replace(".","",$_SERVER[REMOTE_ADDR]) ?>";
   number3 = number2 - number1;
   
   //var trimmed;
   //trimmed = document.getElementById('comment').value.replace(/^\s+|\s+$/g,"[tbbr]");
   var trimmed;
   trimmed = document.getElementById('comment').value.replace(/\n/g,"[tbbr]");
   trimmed = escape(trimmed);
   
   var m1 = parseInt(document.getElementById('math1').value);
   var m2 = parseInt(document.getElementById('math2').value);
   var answer = m1 + m2;
   
   
   if (trimmed.length > 0)
      {		

      var url = "http://<? echo $this_host . $tbrootdir; ?>?a=addcomment";
               
      if (document.getElementById('commenttypenew').checked == false)
         {
         var params="key="+ number3 +"&sid=" + Math.random()+ "&answer=" + answer + "&ape=" + document.getElementById('ape').value + "&a=addcomment&childof=" + document.getElementById('threadid').value + "&tbalias=" + document.getElementById('tbalias').value + "&data=" + trimmed;         
         }
      else
         {
         var params="key="+ number3 +"&sid=" + Math.random()+ "&answer=" + answer + "&ape=" +document.getElementById('ape').value + "&a=addcomment&tbalias=" + document.getElementById('tbalias').value + "&data=" + trimmed;
         }
      
      xmlhttp.open("POST", url, true);
      xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xmlhttp.setRequestHeader("Content-length", params.length);
      xmlhttp.setRequestHeader("Connection", "close");

      xmlhttp.onreadystatechange=function()
         {
         if (xmlhttp.readyState==4)
            {
            tb_getmath();
            response = xmlhttp.responseText;
            var response2 = response.split("[|tbmaxdate|]");
            var maxdate = response2[0];
            document.getElementById('newest').value = maxdate;
            response = response2[1];
            
            document.getElementById('tb_threads').innerHTML = response;
            //loadthreads();
            document.getElementById('comment').value = "";
            updatemeta();
            }
         };
      
      //xmlhttp.setRequestHeader('Accept','message/x-jl-formresult');
      xmlhttp.send(params);
    
      //xmlhttp.send(null);
      return false;	
      }
   else
      {
      alert('Writing Anything?');			
      }
   }

function activatenew()
   {
   document.getElementById('commenttypereply').checked = false;
   }

function activatereply()
   {
   document.getElementById('commenttypenew').checked = false;
   }
</script>
<style type='text/css'>
body 
   {
   font: 0.7em/160% Verdana, Arial, Helvetica, sans-serif;
   }
a
   {
   text-decoration:none;}
.hideit 
   {
   display: none;
   }
.showit 
   {
   display: block;
   }
.tbtitle
   {
   text-decoration:none;
   color: #ffffff;
   font-size: 1.2em;
   }
.wob
   {
   color: orange;
   font-size: 1.0em;
   }
a:visited
   {
   text-decoration:none;
   }
a:hover
   {
   text-decoration:underline;		
   }
.threadstamp
   {
   color: #AF9e4b;
   background: white;
   font-family: <? echo $tbfont; ?>;
   <?
   if ($_GET[small] == "true" || ($_GET[small] != "true" && intval(strip_tags($_GET[userx1])) < 300 && strlen(trim($_GET[userx1])) > 0))
      {
      echo "font-size: 8px;";
      echo "height: 8px;";	
      }
   else
      {
      echo "font-size: 11px;";
      echo "height: 11px;";	
      }
   ?>
   }
.spacerclass
   {
   background: white;
   font-family: <? echo $tbfont; ?>;
   font-size: 1.0em;
   }
.msgfooter
   {
   color: #333333;
   background: #cccccc;
   border: 0px solid #999999;
   padding: 2px 2px 2px 2px;
   }
.selectedtb
   {
   background: yellow;
   border: 0px solid;
   padding:1px;
   text-decoration:none;
   outline: none;
   }
.unselectedtb
   {
   background: white;
   text-decoration:none;
   outline: none;
   }
A:HOVER
   {
   text-decoration:none;
   }
A
   {
   outline : none; 
   }
.cwthreadbody
   {
   color: #333333;
   <?
   if ($_GET[fullscreen]=="true")
      {
      echo "width: 50%;\n";
      echo "height: 100%;\n";
      }
   else
      {
      echo "width: " . round($tb_width_1,0) . "px;\n";
      echo "height: " . round($tb_height,0) . "px;\n";
      }
   ?>
   background: #ffffff;
   font-family: <? echo $tbfont; ?>;
   line-height: 1.1em;   
   <?
   if ($_GET[small] == "true" || ($_GET[small] != "true" && intval(strip_tags($_GET[userx1])) < 300 && strlen(trim($_GET[userx1])) > 0))
      {
      echo "font-size: 11px;";
      }
   else
      {
      echo "font-size: 12px;";
      }
      ?>
   border:0px;
   white-space: nowrap;
   overflow: scroll;       
   }
pre 
   {
   font-family: <? echo $tbfont; ?>; 
   white-space: pre-wrap;       /* css-3 */
   white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
   white-space: -pre-wrap;      /* Opera 4-6 */
   white-space: -o-pre-wrap;    /* Opera 7 */
   word-wrap: break-word;       /* Internet Explorer 5.5+ */
   }

.cwmeta
   {
   vertical-align: top;
   color: #ffffff;
   background: #<? echo strip_tags($tbcolor2); ?>;
   font-family: <? echo $tbfont; ?>;
   <?
   if ($_GET[small] == "true" || ($_GET[small] != "true" && intval(strip_tags($_GET[userx1])) < 300 && strlen(trim($_GET[userx1])) > 0))
      {
      echo "font-size: 11px;";
      }
   else 
      {	
      echo "font-size: 12px;";
      }
   ?>
   border-bottom:0px solid #<? echo strip_tags($tbcolor2); ?>;
   border-top: 0px solid #<? echo strip_tags($tbcolor2); ?>;
   border-left: 0px solid #<? echo strip_tags($tbcolor2); ?>;
   border-right: 0px solid #<? echo strip_tags($tbcolor2); ?>;
   padding: 10px;
   margin: 0px;
   <?
   if ($_GET[fullscreen]!="true")
      {
      echo "width: 100%;\n";
      }
   ?>
   }
.cwmetaspan
   {
   vertical-align: top;
   color: #ffffff;
   background: #<? echo strip_tags($tbcolor2); ?>;
   font-family: <? echo $tbfont; ?>;
   <?
   if ($_GET[small] == "true" || ($_GET[small] != "true" && intval(strip_tags($_GET[userx1])) < 300 && strlen(trim($_GET[userx1])) > 0))
      {
      echo "font-size: 11px;";
      }
   else 
      {	
      echo "font-size: 12px;";
      }
   if ($_GET[fullscreen]!="true")
      {
      echo "width: 100%;\n";
      }
   ?>
   }
.cwmsgbody
   {
   color: #333333;
   line-height: 1.1em; 
   <?
   if ($_GET[fullscreen]=="true")
      {
      echo "width: 50%;\n";
      echo "height: 100%;\n";
      }
   else
      {
      echo "width: " . round($tb_width_2,0) . "px;\n";
      echo "height: " . round($tb_height,0) . "px;\n";
      }
   ?>
   background: #ffffff;
   <?
   if ($_GET[small] == "true" || ($_GET[small] != "true" && intval(strip_tags($_GET[userx1])) < 300 && strlen(trim($_GET[userx1])) > 0))
      {
      echo "font-size: 11px;";	
      }
   else 
      {	
      echo "font-size: 12px;";	
      }
   ?>
   border: 0px;
   overflow: auto;
   font-family: <? echo $tbfont; ?>; 
   white-space: pre-wrap;       /* css-3 */
   white-space: -moz-pre-wrap;  /* Mozilla, since 1999 */
   white-space: -pre-wrap;      /* Opera 4-6 */
   white-space: -o-pre-wrap;    /* Opera 7 */
   word-wrap: break-word;       /* Internet Explorer 5.5+ */
   }
.cwcomment
   {
   color: #ffffff;
   background: #<? echo strip_tags($tbcolor1); ?>;
   font-family: <? echo $tbfont; ?>;
   <?
   if ($_GET[small] == "true" || ($_GET[small] != "true" && intval(strip_tags($_GET[userx1])) < 300 && strlen(trim($_GET[userx1])) > 0))
      {
      echo "font-size: 11px;";	
      }
   else 
      {	
      echo "font-size: 12px;";	
      }
   ?>
   border-top: 0px solid #<? echo strip_tags($tbcolor2); ?>;
   border-bottom: 0px solid #<? echo strip_tags($tbcolor2); ?>;
   border-left: 0px solid #<? echo strip_tags($tbcolor2); ?>;
   border-right: 0px solid #<? echo strip_tags($tbcolor2); ?>;
   padding: 10px 10px 10px 10px;
   margin: 0px;
   }
	
.cwtop
   {
   color: #ffffff;
   background: #<? echo strip_tags($tbcolor2); ?>;
   font-family: <? echo $tbfont; ?>;
   <?
   if ($_GET[small] == "true" || ($_GET[small] != "true" && intval(strip_tags($_GET[userx1])) < 300 && strlen(trim($_GET[userx1])) > 0))
      {
      echo "font-size: 11px;";	
      }
   else 
      {	
      echo "font-size: 12px;";	
      }
   ?>
   border-top: 0px solid #<? echo strip_tags($tbcolor2); ?>;
   border-bottom: 0px solid #<? echo strip_tags($tbcolor2); ?>;
   border-left: 0px solid #<? echo strip_tags($tbcolor2); ?>;
   border-right: 0px solid #<? echo strip_tags($tbcolor2); ?>;
   /* padding: 2px 2px 2px 2px; */
   margin: 0px;
   vertical-align:center;
   }
.cwtoplink
   {
   font-family:<? echo $tbfont; ?>;
   <?
   if ($_GET[small] == "true" || ($_GET[small] != "true" && intval(strip_tags($_GET[userx1])) < 300 && strlen(trim($_GET[userx1])) > 0))
      {
      echo "font-size: 11px;";	
      }
   else 
      {	
      echo "font-size: 12px;";	
      }
   ?>
   color: #ffffff;
   cursor: pointer;
   vertical-align:center;	
   }
.cwcommenttable
   {
   color: #ffffff;
   background: #<? echo strip_tags($tbcolor1); ?>;
   font-family: <? echo $tbfont; ?>;
   <?
   if ($_GET[small] == "true" || ($_GET[small] != "true" && intval(strip_tags($_GET[userx1])) < 300 && strlen(trim($_GET[userx1])) > 0))
      {
      echo "font-size: 11px;";	
      }
   else 
      {	
      echo "font-size: 12px;";	
      }
   ?>
   }
</style>
<?
if ($_GET[fullscreen]=="true")
  	{
  	echo "<table cellpadding=0 cellspacing=0 style='height:inherit;table-layout:fixed;width:100%;max-width:100%;margin:0px;padding:0px;' height=\"100%\" width=\"100%\">";
  	}
else
  	{
  	echo "<table cellpadding=0 cellspacing=0>";
  	}
    echo "<tr>";
    if ($_GET[iframe]!='true')
        {
        echo "<td style='padding:0px;text-align:right;width:100%;' colspan=2>";           
        }
    else
        {
        echo "<td style='padding:0px;text-align:left;width:100%;' colspan=2 >";
        }
                
    if ($_GET[iframe]!='true')
        {
        echo "<div class='cwtop' name='cwtop' id='cwtop'>";                      
        echo "<b>";
        echo "&nbsp;<a class='cwtoplink' href='". $tbrootdir ."'>home</a> <b style='color:#". $tbcolor1 .";'>|</b>
              <samp class='cwtoplink' onClick='newchan()'>new channel</samp> <b style='color:#". $tbcolor1 .";'>|</b>&nbsp;";              
              if ($_GET[fullscreen]!="true")
                	{
                 echo "<a class='cwtoplink' target='_blank' href='". $tbrootdir ."?iframe=true&fullscreen=true' title='Full Screen Mode'>fullscreen mode</a> <b style='color:#". $tbcolor1 .";'>|</b> ";
                 }
        echo "<a class='cwtoplink' target='_blank' href='threadbuddy.php?a=viewplain' title='Plaintext Threads'>plaintext</a> <b style='color:#". $tbcolor1 .";'>|</b>
              <a class='cwtoplink' href='javascript:tbpopup()' title='Popup Version'>popup version</a> <b style='color:#". $tbcolor1 .";'>|</b>              <a class='cwtoplink' href='threadbuddy.php?a=help'>help</a> <b style='color:#". $tbcolor1 .";'>|</b>
              <a class='cwtoplink' href='threadbuddy.php?a=about'>about</a><b style='color:#". $tbcolor1 .";'>|</b>
              <a class='cwtoplink' target='_blank' href='threadbuddy.php?a=rss' title='RSS Comments'>
              <img border=0 style='margin-bottom:2px;vertical-align:bottom;' class='cwtoplink' src='rss-small2.gif'></a>&nbsp;";
       echo "</b>";
       echo "</div>";
        }
    else
        {
        if ($_GET[fullscreen]=="true")
          	{
           echo "<div class='cwtop' name='cwtop' id='cwtop' style='float:left;width:100%;spacing:0px;padding:0px;'>";
           }
        else
           {
           echo "<div class='cwtop' name='cwtop' id='cwtop' style='float:left;width:100%;spacing:0px;padding:0px;'>";           
           }
        echo "<span class='cwtop' name='cwtop' id='cwtop' style='min-width:150;text-align:left;float:left;'>";
          echo "<b>";
          echo "&nbsp;Discussion Channel: &nbsp;<font color='orange'>" . $thistitle . "</font>";
          echo "</b>";
        echo "</span>";
        echo "<span class='cwtop' name='cwtop' id='cwtop' style='margin-top:2px;margin-bottom:2px;min-width:150;float:right;text-align:right;'>";
          echo "<b>";
          echo "<a class='cwtoplink' target='_blank' href='threadbuddy.php?a=viewplain' title='Plaintext Threads'>plaintext</a>&nbsp;&nbsp;";
          echo "<a class='cwtoplink' target='_blank' href='threadbuddy.php?a=rss' title='RSS Comments'>
                <img border=0 style='margin-top:2px;' class='cwtoplink' src='rss-small2.gif'>&nbsp;
                </a>";
          echo "</b>";
        echo "</span>";
        echo "</div>";
        }
        
    echo "</td>";
    echo "</tr>";
    echo "<tr>";
    
    $minusheight = 265;    
    if ($_GET[fullscreen] == "true")
       {
       echo "<td style='width:50%;height:100%;height:expression(document.body.clientHeight - ". intval($minusheight - 32) ." + \"px\");' colspan=1 height=\"100%\">";
       echo "<div class='cwthreadbody' name='tb_threads' id='tb_threads' style='width:100%;'></div>";
       echo "</td>";
       }
    else
       {
       echo "<td style='padding:0px;' colspan=1>";
       echo "<div class='cwthreadbody' name='tb_threads' id='tb_threads'>";
       echo "</div>";
       echo "</td>";
       }    
    if ($_GET[fullscreen] == "true")
       {
       echo "<td style='width:50%;height:100%;height:expression(document.body.clientHeight - ". intval($minusheight - 32) ." + \"px\");' valign=top colspan=1>";
       echo "<div class='cwmsgbody' style='width:100%;'>";
       echo "<div name='tb_msg' id='tb_msg' style='padding-left:5px;'></div>";
       echo "</div>";
       echo "</td>";
       }
    else
       {
       echo "<td style='padding:0px;' colspan=1>";
       echo "<div class='cwmsgbody' >";
       echo "<div name='tb_msg' id='tb_msg' style='padding-left:5px;'></div>";       
       echo "</div>";
       echo "</td>";
       }


    echo "</tr>";
    
    echo "<tr>";
    if ($_GET[fullscreen] == "true")
       {
       echo "<td colspan=2 style='padding:0px;margin:0px;width:100%;'>";
       }
    else
       {
       echo "<td colspan=2 style='padding:0px;margin:0px;width:100%;'>";       
       }
    
        // Begin bottom area
        echo "<table cellpadding=0 cellspacing=0 border=0 width=100%>";
        echo "<tr>";
        echo "<td style='padding:0px;'>";
            echo "<div class='cwcomment'>";
                    echo "<input type='checkbox' name='commenttypenew' id='commenttypenew' value='new' checked onclick='javascript:activatenew()'> 
                           New Thread<br />";
                    echo "<input type='checkbox' name='commenttypereply' id='commenttypereply' value='reply' disabled onclick='javascript:activatereply()'>";
                    echo " Reply to Selected<br />";
                    echo "<input type='hidden' name='math1' id='math1' value='none'>";
                    echo "<input type='hidden' name='math2' id='math2' value='none'>";
                    echo "<input type='hidden' name='threadid' id='threadid' value='none'>";
                    echo "<input type='hidden' name='ape' id='ape' value='none'>";                    
                    echo "<input type='hidden' name='newest' id='newest' value='none'>";
                
                echo "<table class='cwcommenttable' cellpadding=0 cellspacing=0 style='vertical-align:middle;width:100%;'>";
                    echo "<tr>";
                        echo "<td class='cwcommenttable' nowrap width=100% style='padding-top:6px;width:100%;'><b>Comment</b><br>";
                            if ($_GET[small]==true)
                                {
                                echo "<textarea style='background: #ffffff; color: #000000; border: 1px solid #000000;' name='comment' id='comment' cols=". round($tb_width_1 / 7.2,0) ." rows=2>";
                                echo "</textarea>";
                                }
                            else
                                {
                                if (strlen(trim(strip_tags($_GET[userx1]))) > 0 && strlen(trim(strip_tags($_GET[userx2]))) > 0)
                                   {
                                   if ((intval(strip_tags($_GET[userx1])) + intval(strip_tags($_GET[userx2]))) < 600)
                                     {
                                     $tbtarows = "1";
                                     }
                                   else
                                     {
                                     $tbtarows = "4";                                     
                                     }
                                   }
                                else
                                   {
                                   $tbtarows = "4";                                     
                                   }
                             				if ($_GET[fullscreen]=="true")
                             					  {
   	                                echo "<textarea style='background: #ffffff; color: #000000; border: 1px solid #000000;' name='comment' id='comment' cols=70 rows=". $tbtarows .">";
           	                        echo "</textarea>";
                             			  		}
                             				else
                             	  				{
                             	  				if ((strlen(trim($_GET[userx1])) > 0 && strlen(trim($_GET[userx1])) > 0) && (intval($_GET[userx1]) + intval($_GET[userx2])) < 500 )
                             	  				   {
      	                                echo "<textarea style='background: #ffffff; color: #000000; border: 1px solid #000000;' name='comment' id='comment' cols=20 rows=". $tbtarows .">";
              	                        }
              	                     else
                             	  				   {
      	                                echo "<textarea style='background: #ffffff; color: #000000; border: 1px solid #000000;' name='comment' id='comment' cols=". round($tb_width_1 / 7.2,0) ." rows=". $tbtarows .">";
              	                        }
           	                        echo "</textarea>";
                               					}
                                }
                            echo "<br><b>Alias</b><br>";
                            if (strlen(trim($_COOKIE[tbalias])) > 0)
                            	{
                            	$alias = strip_tags($_COOKIE[tbalias]);	
                            	}
                            else 
                            	{
                            	if (strlen(trim($_GET[sitealias]))>0)
                            	   {
                            	   $alias = trim(strip_tags($_GET[sitealias]));
                                }
                             else                                
                            	   {
                            	   $alias = $_SERVER[REMOTE_ADDR];
                            	   }
                            	}
                            if ($_GET[aliaslock]==true)
                              {
                              echo "<input type='text' disabled size=20 maxsize=20 name='tbalias' id='tbalias' value='". $alias ."' 
                                   style='background: #ffffff;color: #000000;border: 1px solid #000000;'>";                          
                              }
                            else
                              {
                              echo "<input type='text' size=20 maxsize=20 name='tbalias' id='tbalias' value='". $alias ."' 
                                   style='background: #ffffff;color: #000000;border: 1px solid #000000;'>";
                              
                              }

                            echo "<span name='submit' id='submit' onClick='javascript:tb_addcomment();' style='vertical-align:middle;margin:0px;line-height:10px;'>
                                  &nbsp;&nbsp;<img name='postbutton' id='postbutton' src='button_0.gif' onMouseOut=\"javascript:document.getElementById('postbutton').src='button_0.gif';\" onMouseOver=\"javascript:document.getElementById('postbutton').src='button_1.gif';\" style='vertical-align:middle;padding-bottom:4px;border:0px;'>";
                            echo "</span>";
                            echo "<span style='float:right;valign:middle;'>";
                            echo "<a style='outline:none;' target='_blank' href='http://threadbuddy.com'><img style='outline:none;' border=0 src='threadbuddy.png'></a>&nbsp;";
                            echo "</span>";                            
                        echo "</td>";
                    echo "</tr>";
                echo "</table>";
            echo "</div>";
        echo "</td>";
        echo "<td class='cwmeta' style='min-width:30%;width:30%;>";
            echo "<span class='cwmetaspan' id='tb_meta' name='tb_meta' style='display:block;min-width:30%;width:30%;'>";
	           echo "</span>";
        echo "</td>";
        echo "</tr>";
        echo "</table>";
        
    echo "</td>";
    echo "</tr>";
echo "</table>";
echo "<script>";
echo "pageload();\n";
echo "</script>";

?>
